<template>
  <business-layout title='算法配置管理'>
    <div class='table-operator' slot='query'>
      <a-form :form='form' layout='inline' @submit='handleQueryData'>
        <a-form-item label=''>
          <a-input placeholder='请输入任务名称' v-decorator='["taskName"]' />
        </a-form-item>
        <a-form-item>
          <a-button type='primary' html-type='submit'>
            <a-icon type='search' />
            查询
          </a-button>

          <a-button html-type='reset' @click='handleResetData'>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <div slot='btns'>
      <a-dropdown v-if='selectedRowKeys.length > 0' style='margin-right: 10px'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='handleDeletes'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'>
          批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
      <a-button type='primary' icon='plus' @click='handleAdd'>新增</a-button>
    </div>

    <s-table
      ref='table'
      size='default'
      rowKey='id'
      :alert='true'
      :columns='columns'
      :data='loadData'
      :rowSelection='rowSelection'
      showPagination='auto'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='dependOnAlgorithmNames' slot-scope='text, record'>
        <span v-if='record.dependOnAlgorithmNames'>
            <a-tag v-for='(item, index) in record.dependOnAlgorithmNames.split(",")' :key='index'>{{ item }}</a-tag>
        </span>
      </span>

      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handleEdit(record)'>编辑</a>
          <a-divider type='vertical' />
          <a @click='handleView(record)'>查看</a>
        </template>
      </span>
    </s-table>

    <create-task-fun
      ref='createModal'
      :visible='visible'
      :can-edit='canEdit'
      :loading='confirmLoading'
      :model='mdl'
      @cancel='handleCancel'
      @ok='handleOk'
    />
  </business-layout>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { findByPage, createAlgorithmTask, updateAlgorithmTask, batchDeleteAlgorithmTasks } from '@/api/algorithmTask'

import CreateTaskFun from './modules/CreateTaskFun.vue'
import CreateTask from '@/views/cfg/modules/CreateTask.vue'

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '算法任务名称',
    dataIndex: 'taskname'
  },
  {
    title: '模块',
    dataIndex: 'moduleName'
  },
  {
    title: '算法',
    dataIndex: 'algorithmName'
  },
  {
    title: '依赖算法',
    dataIndex: 'dependOnAlgorithmNames',
    scopedSlots: { customRender: 'dependOnAlgorithmNames' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'TableList',
  components: {
    CreateTask,
    CreateTaskFun,
    STable,
    Ellipsis
  },
  data() {
    this.columns = columns
    return {
      activeKey: '1',
      // create model
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      mdl: null,
      canEdit: true,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return findByPage(requestParameters).then(res => {
          console.log(res, 'res', '///////////')
          return res
        })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {},

  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleAdd() {
      this.mdl = null
      this.canEdit = true
      this.visible = true
    },
    handleDeletes() {
      const that = this
      this.$confirm({
        title: '提示?',
        content: '当前操作不可逆、是否继续？',
        okType: 'danger',
        async onOk() {
          const result = await batchDeleteAlgorithmTasks(that.$refs.table.selectedRowKeys)
          if (result) {
            that.$message.success('删除成功')
            that.$refs.table.clearSelected()
            that.$refs.table.refresh()
          }
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    handleView(record) {
      this.visible = true
      this.canEdit = false
      this.mdl = {
        ...record,
        dependOnAlgorithmNames: record.dependOnAlgorithmNames ? record.dependOnAlgorithmNames.split(',').map(item =>item) : []
      }
    },
    handleEdit(record) {
      this.visible = true
      this.canEdit = true
      this.mdl = {
        ...record,
        dependOnAlgorithm: record.dependOnAlgorithm ? record.dependOnAlgorithm.split(',').map(item => Number(item)) : [],
        dependOnAlgorithmNames: record.dependOnAlgorithmNames ? record.dependOnAlgorithmNames.split(',') : []
      }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields(async (errors, values) => {
        if (!errors) {
          values.dependOnAlgorithm = values.dependOnAlgorithm ? values.dependOnAlgorithm.join(',') : ''
          console.log(values, 'dependOnAlgorithmdependOnAlgorithmdependOnAlgorithm')
          if (values.id > 0) {
            try {
              const result = await updateAlgorithmTask(values)
              if (result) {
                this.visible = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()

                this.$message.success('更新成功')
              }
            } finally {
              this.confirmLoading = false
            }
          } else {
            try {
              const result = await createAlgorithmTask(values)
              if (result) {
                this.visible = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()

                this.$message.success('新增成功')
              }
            } finally {
              this.confirmLoading = false
            }
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.success(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleQueryData(e) {
      e.preventDefault()
      const form = this.form
      const that = this
      const queryObj = {}
      form.validateFields((error, values) => {
        Object.keys(values).forEach(key => {
          console.log(values[key], 'values[key]values[key]')
          if (values[key]) {
            queryObj[key] = values[key]
          }
        })
        this.queryParam = queryObj
        that.$refs.table.refresh()
      })
    },
    handleResetData() {
      this.queryParam = {}
      this.form.resetFields()
      this.$refs.table.refresh()
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang='less' scoped>
.table-tab {

}
</style>
